package com.guashu.jaywayjsonpath.renhang;

import com.alibaba.fastjson.JSON;
import com.guashu.jaywayjsonpath.enums.PbocTable;
import com.guashu.jaywayjsonpath.util.DealMessageUtil;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import net.minidev.json.JSONArray;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import com.guashu.jaywayjsonpath.util.JawJsonPathUtil;

public class InsertData {

    public static void main(String[] args) {

        String jsonFilePath = "E:\\国银租赁\\需求\\20240201-人行指标\\人行报文.json"; // JSON文件路径
        /**
         * 类型
         * 1、dim 无数组
         * 2、detail 只有一维数组
         * 3、detail 一二维数组
         */
        try {
            String jsonStr = new String(Files.readAllBytes(Paths.get(jsonFilePath)), StandardCharsets.UTF_8);
            Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonStr);
            //String st11 = DealMessageUtil.safelyReadJsonPath(document, "$.PNO.PC03.PC030H[?(@.PC030D01 == '1')].PC030S02");
            Object pa01bi01 = JawJsonPathUtil.readPath(document, "$.PRH.PA01.PA01B.PA01BI01");
            Object s11= JsonPath.read(document,"$.PPO.PC04.PC040H[?(@.PC040D01 == '1')].PC040D01");
            String s12= JsonPath.read(document,"concat($.PPO.PC04.PC040H[?(@.PC040D01 == '1')].PC040D01)");
            String s13= JsonPath.read(document,"concat($.POS.PG01[*].PG010H)");

            //String strTmp= DealMessageUtil.safelyReadJsonPathToString(document, "$.PNO.PC03.PC030H[?(@.PC030D01 == '1')].PC030S02");
            //String test1=DealMessageUtil.safelyReadJsonPathToString(document, "$.PPO.PC04.PC040H[?(@.PC030D01 == '1')].PC040D01");
            Object r11=JsonPath.read(document,"$.PPO.PC04.PC040H[?(@.PC040D01 == '1')].PC040D01");
            Object r12=JsonPath.read(document,"$.PPO.PC04.PC040H[?(@.PC040D01 == '1')].PC040S02");
            Object r13=JsonPath.read(document,"$.PPO.PC04.PC040H[?(@.PC040D01 == '1')].PC040J01");
            Object r21=JsonPath.read(document,"$.PPO.PC04.PC040H[?(@.PC040D01 == '2')].PC040D01");
            Object r22=JsonPath.read(document,"$.PPO.PC04.PC040H[?(@.PC040D01 == '2')].PC040S02");
            Object r23=JsonPath.read(document,"$.PPO.PC04.PC040H[?(@.PC040D01 == '2')].PC040J01");
            Object r31=JsonPath.read(document,"$.PPO.PC04.PC040H[?(@.PC040D01 == '3')].PC040D01");
            Object r32=JsonPath.read(document,"$.PPO.PC04.PC040H[?(@.PC040D01 == '3')].PC040S02");
            Object r33=JsonPath.read(document,"$.PPO.PC04.PC040H[?(@.PC040D01 == '3')].PC040J01");
            Object r41=JsonPath.read(document,"$.PPO.PC04.PC040H[?(@.PC040D01 == '4')].PC040D01");
            Object r42=JsonPath.read(document,"$.PPO.PC04.PC040H[?(@.PC040D01 == '4')].PC040S02");
            Object r43=JsonPath.read(document,"$.PPO.PC04.PC040H[?(@.PC040D01 == '4')].PC040J01");

            String idCard=pa01bi01.toString();
            // 解析规则封装到Map中
            Map<String, String> fieldJsonPaths = new LinkedHashMap<>();
            fieldJsonPaths.put("pd01ad01", "$.PDA.PD01[*].PD01A.PD01AD01");
            fieldJsonPaths.put("pd01bd01", "$.PDA.PD01[*].PD01B.PD01BD01");
            fieldJsonPaths.put("pd01ai01", "$.PDA.PD01[*].PD01A.PD01AI01");
            fieldJsonPaths.put("pd01er03", "$.PDA.PD01[*].PD01E.PD01EH[*].PD01ER03");
            fieldJsonPaths.put("pd01ed01", "$.PDA.PD01[*].PD01E.PD01EH[*].PD01ED01");
            fieldJsonPaths.put("pd01ej01", "$.PDA.PD01[*].PD01E.PD01EH[*].PD01EJ01");
            // 示例用法
            PbocTable table = PbocTable.PBOC_ACC_INFO; // 更改为所需的表
            // 使用选定的解析策略解析数据
            table.getParserStrategy().parse(table.name());


            Map<String, String> arrayRuleJasonPath = getArrayRuleJasonPathMap(fieldJsonPaths);
            Object pa01bi01Obj = DealMessageUtil.safelyReadJsonPath(document, "$.PRH.PA01.PA01B.PA01BI01");

            Object contactTxt=JsonPath.read(document, "$.POS.PG01[0].PG010H");
            System.out.println("数组："+JSON.toJSONString(contactTxt));
            String PG010H = DealMessageUtil.safelyReadJsonPathToArray(document, "$.POS.PG01[*].PG010H").toString();

            JSONArray oneDimensionalArray = DealMessageUtil.safelyReadJsonPathToArray(document, arrayRuleJasonPath.get("oneArrayJasonPath"));
            List<String> oneDimensionalArrayValueJasonPath = getArrayValueJasonPath(fieldJsonPaths, "[*]", 1);
            List<String> twoDimensionalArrayValueJasonPath = getArrayValueJasonPath(fieldJsonPaths, "[*]", 2);
            List<String> insertTmp = new ArrayList<>();
            for (Object oneDimensionalArrayEle : oneDimensionalArray) {
                String oneElementJson = JSON.toJSONString(oneDimensionalArrayEle); // 将单条记录转换为JSON字符串

                // 创建一个StringBuffer对象
                StringBuffer oneDimensionalArrayEleStringBuffer = new StringBuffer();
                oneDimensionalArrayEleStringBuffer.append(pa01bi01).append(",");
                //获取一维数组的value
                for (String fieldJasonPath : oneDimensionalArrayValueJasonPath) {
                    String value = DealMessageUtil.safelyReadJsonPath(oneElementJson, fieldJasonPath);
                    oneDimensionalArrayEleStringBuffer.append(!StringUtils.isEmpty(value) ? value : "null").append(",");
                }
                String oneDimensionalAwaitInsertStr = oneDimensionalArrayEleStringBuffer.toString();

                //根据一维数组，获取二维数组
                JSONArray towDimensionalArrayFromOne = DealMessageUtil.safelyReadJsonPathToArray(oneElementJson, arrayRuleJasonPath.get("twoArrayJasonPath"));
                if (CollectionUtils.isEmpty(towDimensionalArrayFromOne)) {
                    StringBuffer twoDimensionalArrayEleStringBuffer = new StringBuffer();
                    //如果二维数组为空，则后面元素置为null
                    for (int i = 0; i < twoDimensionalArrayValueJasonPath.size(); i++) {
                        twoDimensionalArrayEleStringBuffer.append("null").append(",");
                    }
                    insertTmp.add(oneDimensionalAwaitInsertStr + twoDimensionalArrayEleStringBuffer.toString());
                } else {
                    //二维数组不为空
                    for (Object twoDimensionalArrayEle : towDimensionalArrayFromOne) {
                        String twoElementJson = JSON.toJSONString(twoDimensionalArrayEle);
                        StringBuffer twoDimensionalArrayEleStringBuffer = new StringBuffer();
                        for (String fieldValueJasonPath : twoDimensionalArrayValueJasonPath) {
                            String value = DealMessageUtil.safelyReadJsonPath(twoElementJson, fieldValueJasonPath);
                            twoDimensionalArrayEleStringBuffer.append(!StringUtils.isEmpty(value) ? value : "null").append(",");
                        }
                        insertTmp.add(oneDimensionalAwaitInsertStr + twoDimensionalArrayEleStringBuffer.toString());

                    }
                }

            }
            System.out.println("detail表插入语句值：" + JSON.toJSONString(insertTmp));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static List<String> getArrayValueJasonPath(Map<String, String> map, String sub, int occurrences) {
        List<String> extractedValues = new ArrayList<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String value = entry.getValue();
            int count = 0;
            int idx = 0;
            while ((idx = value.indexOf(sub, idx)) != -1) {
                count++;
                idx += sub.length();
            }
            if (count == occurrences) {
                int lastIndex = value.lastIndexOf(sub);
                extractedValues.add("$" + value.substring(lastIndex + sub.length()));
            }
        }
        return extractedValues;
    }

    private static Map<String, String> getArrayRuleJasonPathMap(Map<String, String> fieldJsonPaths) {
        //数组表达式单独提出来
        Map<String, String> arrayRuleJasonPath = new HashMap<>();
        // 使用for循环遍历Map
        for (Map.Entry<String, String> entry : fieldJsonPaths.entrySet()) {
            String value = entry.getValue();
            // 找到第一个[*]的位置
            int firstIndex = value.indexOf("[*]");
            if (firstIndex != -1) {
                // 截取第一个[*]左边的字符
                String oneDimensionArrayKey = value.substring(0, firstIndex);
                arrayRuleJasonPath.put("oneArrayJasonPath", oneDimensionArrayKey + "[*]");

                // 由于[*]长度为3，所以从第一个[*]结束的位置开始查找第二个[*]
                int secondIndex = value.indexOf("[*]", firstIndex + 3);
                // 如果找到第二个[*]
                if (secondIndex != -1) {
                    // 截取两个[*]之间的字符串
                    String twoDimensionArrayKey = value.substring(firstIndex + 3, secondIndex);
                    arrayRuleJasonPath.put("twoDimensionArrayKey", "$" + twoDimensionArrayKey + "[*]");
                } else {
                    arrayRuleJasonPath.put("twoDimensionArrayKey", null);
                }
            } else {
                arrayRuleJasonPath.put("oneArrayJasonPath", null);
                arrayRuleJasonPath.put("twoDimensionArrayKey", null);
            }
        }
        return arrayRuleJasonPath;
    }


}
